﻿namespace Sedodream.Web.Common.View.HtmlView
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;  // required for extension methods
    using System.Web.Routing;

    public class HtmlRadioButtonGroup : AbstractHtmlViewObject
    {
private readonly List<SelectListItem> mSelectList;
private readonly bool mCreateLi;

public HtmlRadioButtonGroup(
    IViewRequestContext requestContext, string name, 
    IEnumerable<SelectListItem> selectList, bool createLi, object attributes)
    : base(requestContext, name)
{
    mSelectList = new List<SelectListItem>();
    if (selectList != null)
    {
        mSelectList.AddRange(selectList);
    }

    mCreateLi = createLi;
    Attributes = attributes;
}

public override void StartView()
{
    HttpResponseBase httpResponse = RequestContext.HttpResponse;

    TagBuilder liTagBuilder = new TagBuilder("li");
    if (mCreateLi)
    {
        httpResponse.Write(liTagBuilder.ToString(TagRenderMode.StartTag));
    }

    TagBuilder divTag = new TagBuilder("div");
    divTag.AddCssClass("option-group");
    if (Attributes != null)
    {
        divTag.MergeAttributes(new RouteValueDictionary(Attributes));
    }

    // The Name property should override any passed into the Attributes
    divTag.MergeAttribute("name", Name, true);

    // create the label - TODO: expose a new property for the label text
    TagBuilder labelTag = new TagBuilder("label");
    labelTag.MergeAttribute("for", Name);
    labelTag.SetInnerText(Name);
    httpResponse.Write(labelTag.ToString(TagRenderMode.Normal));

    httpResponse.Write(divTag.ToString(TagRenderMode.StartTag));

    // Write out the radio buttons, let the MVC Helper do the hard work here
    foreach (SelectListItem item in this.mSelectList)
    {
        string text = !string.IsNullOrEmpty(item.Text)
                        ? item.Text
                        : item.Value;

        httpResponse.Write(RequestContext.HtmlHelper.RadioButton(
                Name, item.Value, item.Selected));

        // Note: Because we are using HtmlHelper.RadioButton the <input> 
        //       elements will have duplicate ids
        //       See: http://forums.asp.net/t/1363177.aspx
        //       In order to avoid this we could do this ourselves here
        TagBuilder spanTag = new TagBuilder("span");
        spanTag.SetInnerText(text);
        httpResponse.Write(spanTag.ToString(TagRenderMode.Normal));
    }

    httpResponse.Write(divTag.ToString(TagRenderMode.EndTag));

    if (this.mCreateLi)
    {
        httpResponse.Write(liTagBuilder.ToString(TagRenderMode.EndTag));
    }
}

        public override void EndView()
        {
            // Nothing to do here
        }
    }
}
